<template>
  <div class="app-container">
    <el-button class="add-rate" @click="addRate" type="primary">添加</el-button>
    <el-tabs v-model="activeName" @tab-click="changeTab">
      <el-tab-pane label="公会房间" name="first">
        <!-- 一级表 -->
        <el-table
          style="width: 100%"
          ref="dataList"
          :data="menuList"
          row-key="id"
          border
        >
          <!-- <el-table-column type="selection" width="55"></el-table-column> -->
          <el-table-column prop="id" label="阶梯等级"> </el-table-column>
          <el-table-column prop="coin_min" label="最小流水（金币）">
          </el-table-column>
          <el-table-column prop="coin_max" label="最大流水（金币）">
          </el-table-column>
          <el-table-column prop="rate" label="分成比例"> </el-table-column>
          <el-table-column prop="add_time" label="添加时间">
            <template slot-scope="scope">
              {{ getDate(scope.row.add_time * 1000) }}
            </template>
          </el-table-column>
          <el-table-column prop="admin_account" label="添加人">
          </el-table-column>
          <el-table-column min-width="300" label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                @click="handleUpdate(scope.row)"
                plain
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="mini"
                @click="handleDelete(scope.row)"
                plain
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <!-- <cus-pagination
          v-show="total > 0"
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.perPage"
          @pagination="getList"
        /> -->
      </el-tab-pane>
      <el-tab-pane label="特殊房间" name="second">
        <el-table
          ref="dataList"
          :data="menuList"
          style="margin-bottom: 20px"
          row-key="id"
          border
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column prop="id" label="阶梯等级"> </el-table-column>
          <el-table-column prop="coin_min" label="最小流水（金币）">
          </el-table-column>
          <el-table-column prop="coin_max" label="最大流水（金币）">
          </el-table-column>
          <el-table-column prop="rate" label="分成比例"> </el-table-column>
          <el-table-column prop="add_time" label="添加时间">
            <template slot-scope="scope">
              {{ getDate(scope.row.add_time * 1000) }}
            </template>
          </el-table-column>
          <el-table-column prop="admin_account" label="添加人">
          </el-table-column>
          <el-table-column min-width="300" label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                @click="handleUpdate(scope.row)"
                plain
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="mini"
                @click="handleDelete(scope.row)"
                plain
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <!-- <cus-pagination
          v-show="total > 0"
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.perPage"
          @pagination="getList"
        /> -->
      </el-tab-pane>
      <el-tab-pane label="公会成员" name="third">
        <el-table
          ref="dataList"
          :data="menuList"
          style="margin-bottom: 20px"
          row-key="id"
          border
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column prop="id" label="阶梯等级"> </el-table-column>
          <el-table-column prop="coin_min" label="最小流水（金币）">
          </el-table-column>
          <el-table-column prop="coin_max" label="最大流水（金币）">
          </el-table-column>
          <el-table-column prop="rate" label="分成比例"> </el-table-column>
          <el-table-column prop="add_time" label="添加时间">
            <template slot-scope="scope">
              {{ getDate(scope.row.add_time * 1000) }}
            </template>
          </el-table-column>
          <el-table-column prop="admin_account" label="添加人">
          </el-table-column>
          <el-table-column min-width="300" label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                @click="handleUpdate(scope.row)"
                plain
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="mini"
                @click="handleDelete(scope.row)"
                plain
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <!-- <cus-pagination
          v-show="total > 0"
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.perPage"
          @pagination="getList"
        /> -->
      </el-tab-pane>
      <el-tab-pane label="公会订单" name="fourth">
        <el-table
          ref="dataList"
          :data="menuList"
          style="margin-bottom: 20px"
          row-key="id"
          border
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column prop="id" label="阶梯等级"> </el-table-column>
          <el-table-column prop="coin_min" label="最小流水（金币）">
          </el-table-column>
          <el-table-column prop="coin_max" label="最大流水（金币）">
          </el-table-column>
          <el-table-column prop="rate" label="分成比例"> </el-table-column>
          <el-table-column prop="add_time" label="添加时间">
            <template slot-scope="scope">
              {{ getDate(scope.row.add_time * 1000) }}
            </template>
          </el-table-column>
          <el-table-column prop="admin_account" label="添加人">
          </el-table-column>
          <el-table-column min-width="300" label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                @click="handleUpdate(scope.row)"
                plain
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="mini"
                @click="handleDelete(scope.row)"
                plain
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <!-- <cus-pagination
          v-show="total > 0"
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.perPage"
          @pagination="getList"
        />-->
      </el-tab-pane>
    </el-tabs>
    <!-- 添加 阶梯  -->
    <el-dialog
      v-dialogDrag
      title="添加"
      :visible.sync="dialogFormVisible"
      @close="handleDialogClose"
    >
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="form"
        label-position="right"
        label-width="120px"
        style="width: 400px; margin: 0 auto"
      >
        <el-form-item label="阶梯类型" prop="rateType">
          <el-select filterable
            v-model="form.rateType"
            placeholder="阶梯类型
          "
          >
            <el-option
              v-for="item in rateTypes"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="最小流水(金币)" prop="minWater">
          <el-input-number
            v-model="form.minWater"
            :min="0"
            label=""
          ></el-input-number>
        </el-form-item>
        <el-form-item label="最大流水(金币)" prop="maxWater">
          <el-input-number
            v-model="form.maxWater"
            :min="0"
            label=""
          ></el-input-number>
        </el-form-item>
        <el-form-item label="分成比例" prop="rate">
          <el-input-number
            v-model="form.rate"
            :min="0"
            :max="100"
            label=""
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm()">
          确 认
        </el-button>
      </div>
    </el-dialog>
    <!-- 编辑 阶梯  -->
    <el-dialog
      v-dialogDrag
      title="编辑"
      :visible.sync="dialogFormVisible2"
      @close="handleDialogClose"
    >
      <el-form
        ref="dataForm2"
        :rules="rules"
        :model="form2"
        label-position="right"
        label-width="120px"
        style="width: 400px; margin: 0 auto"
      >
        <el-form-item label="阶梯类型" prop="rateType">
          <el-select filterable
            v-model="form2.rateType"
            placeholder="阶梯类型
          "
          >
            <el-option
              v-for="item in rateTypes"
              :key="item"
              :label="item"
              :value="item"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="最小流水(金币)" prop="minWater">
          <el-input-number
            v-model="form2.minWater"
            :min="0"
            label=""
          ></el-input-number>
        </el-form-item>
        <el-form-item label="最大流水(金币)" prop="maxWater">
          <el-input-number
            v-model="form2.maxWater"
            :min="0"
            label=""
          ></el-input-number>
        </el-form-item>
        <el-form-item label="分成比例" prop="rate">
          <el-input-number
            v-model="form2.rate"
            :min="0"
            :max="100"
            label=""
          ></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="dialogFormVisible2 = false">
          取 消
        </el-button>
        <el-button type="primary" @click="submitForm2()">
          确 认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { saveData, deleteData, updateData, listData } from "@/api/rate/rate";
export default {
  data() {
    return {
      activeName: "first",
      listLoading: true,
      total: 0,
      listQuery: {
        page: 1,
        perPage: 10,
      },
      selectList2: [
        { key: undefined, lab: "全部分类" },
        { key: "1", lab: "待审核 " },
        { key: "2", lab: "已发放" },
        { key: "3", lab: "已冻结" },
      ],
      menuList: [],
      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogStatus: "",
      titleMap: {
        update: "编辑",
        create: "增加",
      },
      form: {
        rateType: "", // 选中的类型
        minWater: null, // 最小金币
        maxWater: null, //最大金币
        rate: null, // 分成比例
      },
      form2: {
        rateType: "", // 选中的类型
        minWater: null, // 最小金币
        maxWater: null, //最大金币
        rate: null, // 分成比例
      },
      rules: {
        rateType: [
          { required: true, message: "请选择阶梯类型", trigger: "change" },
        ],
        minWater: [
          { required: true, message: "请输入最小流水", trigger: "blur" },
        ],
        maxWater: [
          { required: true, message: "请输入最大流水", trigger: "blur" },
        ],
        rate: [{ required: true, message: "请输入分成比例", trigger: "blur" }],
      },
      rules2: {
        memo: [{ required: true, message: "请输入", trigger: "blur" }],
      },
      rateTypes: ["公会房间", "特殊房间", "公会成员", "公会订单"], //阶梯类型
    };
  },
  created() {
    // this.getList();
    this.getRateList(1);
  },
  methods: {
    getLocalTime(nS) {
      return new Date(parseInt(nS) * 1000)
        .toLocaleString()
        .replace(/年|月/g, "-")
        .replace(/日/g, " ");
    },
    getDate(data) {
      let date = new Date(data);
      let Y = date.getFullYear() + "-";
      let M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      let D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      let h =
        (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
      let m =
        (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) +
        ":";
      let s =
        date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
      return Y + M + D + h + m + s;
    },
    getList() {
      this.listLoading = true;
      let urlData = "?";
      if (this.listQuery.page) {
        urlData = urlData + `page=${this.listQuery.page}&`;
      }
      if (this.listQuery.perPage) {
        urlData = urlData + `perPage=${this.listQuery.perPage}`;
      }
      if (this.listQuery.search) {
        urlData = urlData + `&search=${this.listQuery.search}`;
      }
      if (this.listQuery.start_at) {
        urlData = urlData + `&start_at=${this.listQuery.start_at}`;
      }
      if (this.listQuery.end_at) {
        urlData = urlData + `&end_at=${this.listQuery.end_at}`;
      }
      if (this.listQuery.status) {
        urlData = urlData + `&status=${this.listQuery.status}`;
      }
      listData(urlData).then((response) => {
        this.menuList = response.data;
        this.total = response.data.meta.total;
        this.listLoading = false;
      });
    },
    getRateList(i) {
      this.listLoading = true;
      listData("?type=" + i).then((response) => {
        this.menuList = response.data;

        this.total = response.data.length;
        this.listLoading = false;
      });
    },
    handleCreate(row) {
      this.resetForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
    },
    handleUpdate(row) {
      this.dialogStatus = "update";
      this.dialogFormVisible2 = true;
      let i = 1;
      // "公会房间", "特殊房间", "公会成员", "公会订单"
      if (this.activeName === "first") {
        i = "公会房间";
      }
      if (this.activeName === "second") {
        i = "特殊房间";
      }
      if (this.activeName === "third") {
        i = "公会成员";
      }
      if (this.activeName === "fourth") {
        i = "公会订单";
      }
;
      this.form2 = {
        id: row.id,
        rateType: i, // 选中的类型
        minWater: row.coin_min, // 最小金币
        maxWater: row.coin_max, //最大金币
        rate: row.rate, // 分成比例
      };
      // updateData(this.form).then((response) => {
      //   if (response.code === 200) {
      //     this.getList();
      //     this.submitOk("成功");
      //   } else {
      //     this.submitFail("失败");
      //   }
      // });
    },
    handleDelete(row) {
      let data = { id: row.id };
      deleteData(data).then((response) => {
        let i;
        if (this.activeName === "first") {
          i = 1;
        }
        if (this.activeName === "second") {
          i = 2;
        }
        if (this.activeName === "third") {
          i = 3;
        }
        if (this.activeName === "fourth") {
          i = 4;
        }
        if (response.code === 200) {
          this.getRateList(i);
          this.submitOk("删除成功");
        } else {
          this.submitFail("删除失败");
        }
      });
    },
    submitForm() {
      this.$refs["dataForm"].validate((valid) => {

        if (!valid) {
          return;
        }
        // let formData = new FormData();
        // for (let item in this.form) {
        //   this.form[item] === undefined
        //     ? ""
        //     : formData.append(item, this.form[item]);
        // }

        let newData = {};
        newData.type = this.form.rateType;
        newData.coin_min = this.form.minWater;
        newData.coin_max = this.form.maxWater;
        newData.rate = this.form.rate;
        if (newData.type === "公会房间") {
          newData.type = 1;
        }
        if (newData.type === "特殊房间") {
          newData.type = 2;
        }
        if (newData.type === "公会成员") {
          newData.type = 3;
        }
        if (newData.type === "公会订单") {
          newData.type = 4;
        }
        if (newData.coin_min > newData.coin_max) {
          let tmp;
          tmp = newData.coin_min;
          newData.coin_min = newData.coin_max;
          newData.coin_max = tmp;
        }
        saveData(newData).then((response) => {
          if (response.code === 200) {
            this.getRateList(newData.type);
            this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });;
            this.dialogFormVisible = false;
          } else {
            this.$message({
                message: response.message,
                type: 'error'
            });;
          }
        });
      });
    },
    submitForm2() {
      this.$refs["dataForm2"].validate((valid) => {
        if (!valid) {
          return;
        }
        // let formData = new FormData();
        // for (let item in this.form2) {
        //   this.form2[item] === undefined
        //     ? ""
        //     : formData.append(item, this.form2[item]);
        // }
        let t;
        if (this.form2.rateType === "公会房间") {
          t = 1;
        }
        if (this.form2.rateType === "特殊房间") {
          t = 2;
        }
        if (this.form2.rateType === "公会成员") {
          t = 3;
        }
        if (this.form2.rateType === "公会订单") {
          t = 4;
        }
        let newData = {
          id: this.form2.id,
          type: t,
          coin_min: this.form2.minWater,
          coin_max: this.form2.maxWater,
          rate: this.form2.rate,
        };
        if (newData.coin_min > newData.coin_max) {
          let tmp;
          tmp = newData.coin_min;
          newData.coin_min = newData.coin_max;
          newData.coin_max = tmp;
        }
        updateData(newData).then((response) => {
          let i;
          if (this.activeName === "first") {
            i = 1;
          }
          if (this.activeName === "second") {
            i = 2;
          }
          if (this.activeName === "third") {
            i = 3;
          }
          if (this.activeName === "fourth") {
            i = 4;
          }
          if (response.code === 200) {
            this.getRateList(i);
            this.$notify({
                    type:'success',
                    message: '操作成功',
                    position: 'bottom-right',
                    showClose: false,
                    duration: 3000
                });;
            this.dialogFormVisible2 = false;
          } else {
            this.$message({
                message: response.message,
                type: 'error'
            });;
          }
        });
      });
    },
    resetForm() {
      this.form = {
        id: undefined,
        count_time: undefined,
        sociaty_id: undefined,
        sociaty_name: undefined,
        amount: undefined,
        real_rate: undefined,
        real_amount: undefined,
        uid: undefined,
      };
    },
    dataTime(val) {
      let oToday = new Date(val);
      let currentDay = oToday.getDay();
      if (currentDay === 0) {
        currentDay = 7;
      }
      let mondayTime =
        oToday.getTime() - (currentDay - 1) * 24 * 60 * 60 * 1000;
      let sundayTime =
        oToday.getTime() + (7 - currentDay) * 24 * 60 * 60 * 1000;
      return (
        this.timestampToTime(mondayTime) +
        "~" +
        this.timestampToTime(sundayTime)
      );
    },
    timestampToTime(timestamp) {
      let date = new Date(timestamp);
      let Y = date.getFullYear() + "-";
      let M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      let D =
        (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
      let strDate = Y + M + D;
      return strDate;
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose() {
      if (this.$refs["dataForm"]) {
        this.$refs["dataForm"].clearValidate(); // 清除整个表单的校验
      }
    },
    handleDialogClose2() {
      if (this.$refs["dataForm2"]) {
        this.$refs["dataForm2"].clearValidate(); // 清除整个表单的校验
      }
    },
    cutoverWater() {},
    addRate() {
      this.dialogFormVisible = true;
    },
    changeTab(e) {
      this.getRateList(e.index * 1 + 1);
    },
  },
};
</script>
<style>
.add-rate {
  position: absolute;
  right: 33px;
  z-index: 4;
}
</style>
